package controller;

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import model.Game;

/**
 * The controller will contain most of the logic.
 * 
 * @author juice (mwahahah)
 */

public class Controller{
	
	private static Controller instance = null;
	private KeyListener keyListener;
	private int updateInterval;
	private Thread thread;
	private boolean moveRight;
	private boolean moveLeft;
	private Controller(){
		keyListener = new KeyAdapter(){
			public void keyPressed(KeyEvent e){
				handleKeyPressed(e);
			}
			public void keyReleased(KeyEvent e){
				handleKeyReleased(e);
			}
			
		};
		
		Game.getInstance().addKeyListener(keyListener);
		
		Thread thread = new Thread(new Runnable(){
			
			public void run(){
				long start = 0;
				long end = 0;
				while(true){
					try {
					start = System.currentTimeMillis();
					if(moveRight)
//						SmurfDomainLogic.walk(Game.getInstance().id,-20000);
					if(moveLeft)
//						SmurfDomainLogic.walk(Game.getInstance().id,20000);
					end = System.currentTimeMillis();
					
						Thread.sleep(50-(end-start));
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}
		);
		thread.start();	
		
	}
	
	public static Controller getInstance(){
		if(instance == null){
			Controller.instance = new Controller();
		}
		return instance;		
	}
	
	public void handleKeyPressed(KeyEvent e) {
		if(e.getKeyCode() == 32 || e.getKeyCode() == 87){
//			SmurfDomainLogic.jump(Game.getInstance().id, -10);
		}else if(e.getKeyCode() == 68){
			moveRight = true;
		}else if(e.getKeyCode() == 65){
			moveLeft = true;
		}
	}
	
	public void handleKeyReleased(KeyEvent e){
		if(e.getKeyCode() == 68){
			moveRight = false;
		}
		if(e.getKeyCode() == 65){
			moveLeft = false;
		}
	}
	
	public void start(int updateInterval){
		this.updateInterval = updateInterval;
		thread.start();		
	}
	
}
